package com.quectel.core.module.securitypatrol.service.impl;


import cn.hutool.core.lang.func.LambdaUtil;
import com.quectel.constant.core.securitypatrol.SecurityPatrolEventReportConstants;
import com.quectel.constant.global.SystemConstants;
import com.quectel.core.constants.RedisCacheConstants;
import com.quectel.core.module.device.dto.DeviceDto;
import com.quectel.core.module.device.service.DeviceService;
import com.quectel.core.module.securitypatrol.dao.SecurityPatrolTaskDao;
import com.quectel.core.module.securitypatrol.dto.SecurityPatrolEventReportDto;
import com.quectel.core.module.securitypatrol.dto.SecurityPatrolPlanDto;
import com.quectel.core.module.securitypatrol.dto.SecurityPatrolTaskDto;
import com.quectel.core.module.securitypatrol.dto.SecurityPatrolTaskRouteDto;
import com.quectel.core.module.securitypatrol.entity.SecurityPatrolTaskEntity;
import com.quectel.core.module.securitypatrol.service.*;
import com.quectel.core.module.village.service.VillageService;
import com.quectel.util.common.CopyUtils;
import com.quectel.util.kit.CacheKit;
import com.quectel.util.kit.Snowflake;
import com.quectel.util.mybatis.MyBatisPlusUtils;
import org.apache.dubbo.config.annotation.DubboService;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.transaction.annotation.Transactional;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.function.Function;

/**
 * @author caolu
 * @email louis.cao@quectel.com
 * @date 2022/05/07 14:10
 */
@DubboService
public class SecurityPatrolTaskServiceImpl implements SecurityPatrolTaskService {

    private static final Logger LOGGER = LoggerFactory.getLogger(SecurityPatrolTaskServiceImpl.class);

    /**
     * 入参解释:实体id
     */
    private static final Function<Long, String> SECURITY_PATROL_TASK_CACHE_BY_ID_FUNC = id -> String.format(RedisCacheConstants.PROJECT_NAME + "SECURITY_PATROL_TASK_CACHE_BY_ID:%d", id);

    @Autowired
    private SecurityPatrolTaskDao securityPatrolTaskDao;
    @Autowired
    private VillageService villageService;
    @Autowired
    private SecurityPatrolPlanService securityPatrolPlanService;
    @Autowired
    private SecurityPatrolEventReportService securityPatrolEventReportService;
    @Autowired
    private DeviceService deviceService;
    @Autowired
    private SecurityPatrolDeviceSubjectService securityPatrolDeviceSubjectService;
    @Autowired
    private SecurityPatrolSubjectService securityPatrolSubjectService;
    @Autowired
    private SecurityPatrolTaskRouteService securityPatrolTaskRouteService;


    @Override
    public SecurityPatrolTaskDto selectByIdPaddingFieldDeviceList(Long taskId) {
        SecurityPatrolTaskEntity entity = securityPatrolTaskDao.selectById(taskId);
        return paddingFieldDeviceList(CopyUtils.copyObj(entity, SecurityPatrolTaskDto.class));
    }

    private SecurityPatrolTaskDto paddingFieldDeviceList(SecurityPatrolTaskDto dto) {
        if (dto != null) {
            // 生成点位数大于0 填充
            if (dto.getRouteCount() > 0) {
                Map<String, Object> paramsMap = new HashMap<>();
                // 查询任务下的deviceIds ,  task+device  ==> 项目list
                paramsMap.put(LambdaUtil.getFieldName(SecurityPatrolTaskRouteDto::getTaskId), dto.getId());
                List<SecurityPatrolTaskRouteDto> securityPatrolTaskRouteDtos = securityPatrolTaskRouteService.queryList(paramsMap);

                // 设备数组非空 填充点位list
                List<SecurityPatrolTaskDto.ExecInfo> execInfos = new ArrayList<>();
                for (SecurityPatrolTaskRouteDto taskRouteDto : securityPatrolTaskRouteDtos) {

                    DeviceDto deviceDto = deviceService.selectCacheById(taskRouteDto.getDeviceId());
                    SecurityPatrolTaskDto.ExecInfo execInfo = new SecurityPatrolTaskDto.ExecInfo();
                    execInfo.setDeviceId(taskRouteDto.getDeviceId());
                    execInfo.setDeviceName(deviceDto.getName());
                    execInfo.setTaskRouteId(taskRouteDto.getId());
                    execInfo.setCompleteTime(taskRouteDto.getCompleteTime());
                    execInfo.setCreateTime(taskRouteDto.getCreateTime());
                    execInfo.setSkipCheckReasonType(taskRouteDto.getSkipCheckReasonType());
                    execInfo.setSnapshotImg(taskRouteDto.getSnapshotImg());
                    execInfo.setDetail(taskRouteDto.getDetail());
                    execInfo.setAddress(taskRouteDto.getAddress());
                    execInfo.setLng(taskRouteDto.getLng());
                    execInfo.setLat(taskRouteDto.getLat());
                    execInfo.setReportList(securityPatrolEventReportService.selectBySecurityPatrolTaskRouteId(taskRouteDto.getId()));

                    // 设置点位状态
                    Map<String, Object> params = new HashMap<>();
                    params.put(LambdaUtil.getFieldName(SecurityPatrolEventReportDto::getTaskRouteId), taskRouteDto.getId());
                    List<SecurityPatrolEventReportDto> reportDtoList = securityPatrolEventReportService.queryList(params);
                    if (reportDtoList.size() > 0) {
                        // 已存在记录的对点位状态填充 0异常 1正常 2跳检
                        for (int i = 0; i < reportDtoList.size(); i++) {
                            if (reportDtoList.get(i).getStatus().equals(SecurityPatrolEventReportConstants.ReportStatusEnum.STATUS_NORMAL.getStatus())) {
                                execInfo.setStatus(SecurityPatrolEventReportConstants.ReportStatusEnum.STATUS_NORMAL.getStatus());
                            }
                        }

                        for (int i = 0; i < reportDtoList.size(); i++) {
                            if (reportDtoList.get(i).getStatus().equals(SecurityPatrolEventReportConstants.ReportStatusEnum.STATUS_ABNORMAL.getStatus())) {
                                execInfo.setStatus(SecurityPatrolEventReportConstants.ReportStatusEnum.STATUS_ABNORMAL.getStatus());
                            }
                        }

                        for (int i = 0; i < reportDtoList.size(); i++) {
                            if (reportDtoList.get(i).getStatus().equals(SecurityPatrolEventReportConstants.ReportStatusEnum.STATUS_SKIP_INSPECTION.getStatus())) {
                                execInfo.setStatus(SecurityPatrolEventReportConstants.ReportStatusEnum.STATUS_SKIP_INSPECTION.getStatus());
                            }
                        }
                    }
                    execInfos.add(execInfo);
                }
                dto.setExecInfos(execInfos);
            }
        }
        return dto;
    }

    @Override
    public SecurityPatrolTaskDto selectCacheById(Long id) {
        return CacheKit.cacheToRedis(
                () -> selectById(id),
                SECURITY_PATROL_TASK_CACHE_BY_ID_FUNC.apply(id),

                SystemConstants.NOT_NULL_CACHE_EXPIRE_SECONDS
        );
    }

    @Override
    public SecurityPatrolTaskDto selectById(Long id) {
        SecurityPatrolTaskEntity entity = securityPatrolTaskDao.selectById(id);
        return paddingFieldWithDetailInfo(CopyUtils.copyObj(entity, SecurityPatrolTaskDto.class));
    }

    private SecurityPatrolTaskDto paddingFieldWithDetailInfo(SecurityPatrolTaskDto dto) {
        if (dto != null) {
            if (dto.getVillageId() != null) {
                dto.setVillageName(villageService.selectCacheById(dto.getVillageId()).getName());
            }
            if (dto.getPlanId() != null) {
                SecurityPatrolPlanDto securityPatrolPlanDto = securityPatrolPlanService.selectCacheById(dto.getPlanId());
                if (securityPatrolPlanDto != null) {
                    dto.setPlanName(securityPatrolPlanDto.getName());
                }
            }
            if (dto.getRouteCount() > 0) {
                Map<String, Object> paramsMap = new HashMap<>();
                // 查询任务下的deviceIds ,  task+device  ==> 项目list
                paramsMap.put(LambdaUtil.getFieldName(SecurityPatrolTaskRouteDto::getTaskId), dto.getId());

                // 点位list
                List<SecurityPatrolTaskRouteDto> securityPatrolTaskRouteDtos = securityPatrolTaskRouteService.queryList(paramsMap);

                // 设备数组非空 填充点位list
                List<SecurityPatrolTaskDto.ExecInfo> execInfos = new ArrayList<>();
                for (SecurityPatrolTaskRouteDto taskRouteDto : securityPatrolTaskRouteDtos) {

                    DeviceDto deviceDto = deviceService.selectCacheById(taskRouteDto.getDeviceId());
                    if (deviceDto != null) {
                        SecurityPatrolTaskDto.ExecInfo execInfo = new SecurityPatrolTaskDto.ExecInfo();
                        execInfo.setDeviceId(taskRouteDto.getDeviceId());
                        execInfo.setDeviceName(deviceDto.getName());
                        execInfo.setStatus(taskRouteDto.getStatus());
                        execInfos.add(execInfo);
                    }
                }
                dto.setExecInfos(execInfos);
            }
        }
        return dto;
    }

    @Override
    public List<SecurityPatrolTaskDto> queryList(Map<String, Object> params) {
        List<SecurityPatrolTaskEntity> list = securityPatrolTaskDao.queryList(params);
        List<SecurityPatrolTaskDto> result = CopyUtils.copyList(list, SecurityPatrolTaskDto.class);
        String padding = (String) params.get("padding");
        if (org.apache.commons.lang3.StringUtils.isEmpty(padding)) {
            result.forEach(this::paddingField);
        } else {
            result.forEach(this::paddingFieldWithEmp);
        }
        return result;
    }

    private SecurityPatrolTaskDto paddingFieldWithEmp(SecurityPatrolTaskDto dto) {
        if (dto != null) {
            if (dto.getPlanId() != null) {
                SecurityPatrolPlanDto securityPatrolPlanDto = securityPatrolPlanService.selectCacheById(dto.getPlanId());
                if (securityPatrolPlanDto != null) {
                    dto.setPlanName(securityPatrolPlanDto.getName());
                }
            }
        }
        return dto;
    }

    private SecurityPatrolTaskDto paddingField(SecurityPatrolTaskDto dto) {
        if (dto != null) {
            if (dto.getVillageId() != null) {
                dto.setVillageName(villageService.selectCacheById(dto.getVillageId()).getName());
            }
            if (dto.getPlanId() != null) {
                SecurityPatrolPlanDto securityPatrolPlanDto = securityPatrolPlanService.selectCacheById(dto.getPlanId());
                if (securityPatrolPlanDto != null) {
                    dto.setPlanName(securityPatrolPlanDto.getName());
                }
            }
        }
        return dto;
    }

    @Override
    public int queryTotal(Map<String, Object> params) {
        return securityPatrolTaskDao.queryTotal(params);
    }

    @Override
    public Long save(SecurityPatrolTaskDto dto) {
        SecurityPatrolTaskEntity entity = CopyUtils.copyObj(dto, SecurityPatrolTaskEntity.class);
        entity.setId(Snowflake.nextId());
        securityPatrolTaskDao.insert(entity);
        return entity.getId();
    }

    @Override
    public void updateById(SecurityPatrolTaskDto dto) {
        SecurityPatrolTaskEntity entity = CopyUtils.copyObj(dto, SecurityPatrolTaskEntity.class);
        securityPatrolTaskDao.updateById(entity);
        CacheKit.invalidRedisCache(SECURITY_PATROL_TASK_CACHE_BY_ID_FUNC.apply(dto.getId()));
    }

    @Override
    public void updateAllColumnById(SecurityPatrolTaskDto dto) {
        SecurityPatrolTaskEntity entity = CopyUtils.copyObj(dto, SecurityPatrolTaskEntity.class);


        MyBatisPlusUtils.updateAllColumnById(entity, securityPatrolTaskDao);

        CacheKit.invalidRedisCache(SECURITY_PATROL_TASK_CACHE_BY_ID_FUNC.apply(dto.getId()));
    }

    @Override
    public void deleteById(Long id) {
        securityPatrolTaskDao.deleteById(id);

        CacheKit.invalidRedisCache(SECURITY_PATROL_TASK_CACHE_BY_ID_FUNC.apply(id));
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public void deleteBatch(Long[] ids) {
        for (Long id : ids) {
            deleteById(id);
        }
    }
}
